﻿using System.Text.RegularExpressions;
using System.Web;
using EPiServer.Community.Blog;
using JoelAbrahamsson.MetaWeblog;

namespace JoelAbrahamsson.BlogExtensions
{
    public class BlogEntrySlugProvider : IBlogEntrySlugProvider
    {
        private HttpContextBase _httpContext;

        public BlogEntrySlugProvider(HttpContextBase httpContext)
        {
            _httpContext = httpContext;
        }

        public void SetSlug(Entry entry, string slug)
        {
            if (string.IsNullOrEmpty(slug))
                slug = GetDefaultSlug(entry);

            entry.SetSlug(slug);
        }

        public string GetDefaultSlug(Entry entry)
        {
            string slug = ReplaceUnallowedCharacters(entry.Title);
            return _httpContext.Server.UrlEncode(slug);
        }

        public virtual string ReplaceUnallowedCharacters(string slug)
        {
            slug = slug
                .ToLower()
                .Replace("–", "-")
                .Replace(" ", "-")
                .Replace("&", "and")
                .Replace("å", "a")
                .Replace("ä", "a")
                .Replace("ö", "o")
                .Replace("ø", "o");

            while (slug.Contains("--"))
                slug = slug.Replace("--", "-");

            slug = slug.Replace("c#", "c-sharp");

            Regex regex = new Regex(@"([^a-z0-9\-])");
            slug = regex.Replace(slug, string.Empty);

            return slug;
        }

        public string GetSlug(Entry entry)
        {
            return entry.GetSlug();
        }
    }
}
